#include "widget.h"
#include "ui_widget.h"
#include "ControlCAN.h"
#include "QMessageBox"
#include "QDebug"
#include <synchapi.h>  //QSleep
#include "QTimer"
#include "get_can_data.h"
const UCHAR Bsp[17][2]={{0x31,0x1C},{0x18,0x1C},{0x87,0xFF},{0x09,0x1C},{0x83,0xFF},
                   {0x04,0x1C},{0x03,0x1C},{0x81,0xFA},{0x01,0x1C},{0x80,0xFA},
                   {0x00,0x1C},{0x80,0xB6},{0x00,0x16},{0x00,0x14},{0x09,0x6F},
                   {0x04,0x6F},{0x03,0x6F}};

double timeStamp_CAN0=0;

uint SendCnt_CAN0=0;
Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    ShowDataTimer=new QTimer(this);
    connect(ShowDataTimer,&QTimer::timeout,this,&Widget::RealTimeUpdateMsg_CAN0);
}

/**
  *@brief:字符串QString->Hex: "FFFFFFFF"->0xffffffff->unsigned long
  *@param:输入字符串，输出unsigned long
  *@author:Mr ZB
  *@date:
  */

unsigned long Widget::Str_into_ULong(QString s)
{
    bool ok;
    s=s.remove(QRegExp("\\s"));
    QChar str;
    QString str_temp;
    QString s_temp;
    QByteArray bytearry_temp;
    QByteArray bytearry;
    str_temp.clear();
    s_temp.clear();
    bytearry_temp.clear();
    bytearry.clear();
    int len;
    len =s.length();
    if(len!=0){
        if(len%2!=0)
        {
            s_temp.append("0"); //奇数就在开头补0
        }
        s_temp.append(s);
        len =s_temp.length();   //在计算一次len

        for(int i=0;i<len;i++)
        {
            str_temp.clear();
            str = s_temp[i];         //字符串拆成单个字符
            str_temp.append(str);
            //qDebug()<<"str_temp:="<<str_temp;
            bytearry_temp +=static_cast<char>(str_temp.toInt(&ok,16));
        }
        //qDebug()<<"bytearry_temp:="<<bytearry_temp; //\n\x0B\f\n\x01\x0B\x02"
        //qDebug()<<"bytearry_temp.toHex():="<<bytearry_temp.toHex();// "0a0b0c0a010b02"

        unsigned long Code_long = 0;
        len = bytearry_temp.size();
        unsigned long a=0;
        for(int i=0;i<len;i=i+2)
        {
            a=static_cast<unsigned char>(bytearry_temp[i]<<4|bytearry_temp[i+1]);//单个字节的整数值,拼接"0a0b0c0a010b02"
            Code_long = (Code_long<<8) + a;
            //qDebug()<<"a:="<<a;
            //qDebug()<<"Code_long:="<<Code_long;
        }
        qDebug()<<"Code_long:="<<Code_long;
        return Code_long;
    }
    return 0;
}


Widget::~Widget()
{
    delete ui;
    rcvThread = new Get_CAN_Data();
    AnyThread = new Any_CAN_Data();
    connect(this,&Widget::destroyed,this,[=](){
        rcvThread->quit();
        rcvThread->wait();//回收资源
        rcvThread->deleteLater();//封装了delete t1，就是删除子线程
        AnyThread->quit();
        AnyThread->wait();//回收资源
        AnyThread->deleteLater();//封装了delete t1，就是删除子线程
    });
}

#define VCI_USBCAN  VCI_USBCAN1
#define m_DevIndex 0

int TimeOut=0;

//开始
void Widget::on_pushButton_clicked()
{
    if(ui->pushButton->text()=="open")
    {
        ui->pushButton->setText("close");
        DWORD Reserved=0;
        if(VCI_OpenDevice(VCI_USBCAN,m_DevIndex,Reserved)!=1)
        {
            QMessageBox::warning(this,tr(""),"open failed");
            return;
        }
        VCI_INIT_CONFIG InitInfo[1];
        InitInfo->AccCode=Str_into_ULong("00000000");
        InitInfo->AccMask=Str_into_ULong("ffffffff");//屏蔽码
        InitInfo->Filter=static_cast<UCHAR>(1);//滤波方式
        InitInfo->Mode=static_cast<UCHAR>(0);//模式
        InitInfo->Timing0=0x01;//波特率 0x03  0x1c设置的就是125k的波特率
        InitInfo->Timing1=0x1C;//波特率    01 1c   250
        if(VCI_InitCAN(VCI_USBCAN,m_DevIndex,0,InitInfo)!=1)
        {
            VCI_CloseDevice(VCI_USBCAN, m_DevIndex);
            QMessageBox::warning(this,tr(""),"Init-CAN failed!");
            return;
        }
        Sleep(100);
        if(VCI_StartCAN(VCI_USBCAN,m_DevIndex,0)!=1)
        {
            QMessageBox::warning(this,tr(""),"Start-CAN0 failed!");
            return;
        }
        //开接收数据的线程
        ShowDataTimer->start(1000); //30ms 触发一次定时器
        rcvThread = new Get_CAN_Data();
        rcvThread->start();
        //解析收到的数据
        AnyThread = new Any_CAN_Data();
        AnyThread->start();
    }else
    {
        ui->pushButton->setText("open");
        rcvThread->exit();
        AnyThread->exit();
        free(rcvThread);
        free(AnyThread);
        ShowDataTimer->stop();
        VCI_ClearBuffer(VCI_USBCAN, 0, 0);//清理接收和发送缓冲器数据 0 1都得清理  否则会关闭失败
        VCI_ClearBuffer(VCI_USBCAN, 0, 1);
        if(VCI_CloseDevice(VCI_USBCAN,0)!=1)
        {
            QMessageBox::warning(this,tr(""),"Close failed！");
            return;
        }
        QMessageBox::information(this,tr(""),"Close successful!");
    }
}

//更新控件
void Widget::RealTimeUpdateMsg_CAN0()
{
    TimeOut++;
    if(TimeOut<3)
    {
        this->ui->TXTshow->setText(hex2Str((unsigned char*)g_data1,8));
        this->ui->TXTshow->append( hex2Str((unsigned char*)g_data2,8));
    }else
    {
        this->ui->TXTshow->setText("");
    }
}

//处理can数据
void Widget::AddRowRecv_CAN0(PVCI_CAN_OBJ Recv)
{
    //QString index=QString::number(RecvCnt_CAN0);            //序号
    QString id=QString::number(Recv->ID,16).toUpper();//帧ID toUpper:将字符c转换为大写英文字母
    QString format;             //帧格式:0=数据帧，1=远程帧
    if(QString::number(Recv->RemoteFlag,16).toInt() == 0)
    {
        //获取是否为远程帧  1是  0否
    }
    if(QString::number(Recv->RemoteFlag,16).toInt() == 1)
    {
        //获取是否为远程帧  1是  0否
    }
    QString type;               //帧类型:0=标准帧，1=扩展帧
    if(QString::number(Recv->ExternFlag,16).toInt() == 0)
    {
        //获取是否为扩展帧  1是  0否
    }
    if(QString::number(Recv->ExternFlag,16).toInt() == 1)
    {
        //获取是否为扩展帧  1是  0否
    }
    QString datalen=QString::number(Recv->DataLen,10);  //数据长度
    QString data=hex2Str(Recv->Data,Recv->DataLen);     //数据
    ui->textEdit->append(id+" "+data);
}

QString Widget::hex2Str(unsigned char *in, int len)
{
    QString s;
    for(int i=0;i<len;i++)
    {
        s+=QString("%1").arg(in[i]&0xFF,2,16,QLatin1Char('0')).toUpper();//toUpper，小写转大写
        s.append(" ");//追加空格
    }
    return s;
}


//发送can数据
void Widget::on_pushButton_2_clicked()
{
    QString sendMsg;//从别处获取要发送的数据
    CAN0_Send_fun(sendMsg);
}


void Widget::CAN0_Send_fun(QString sendMsg)
{
    QString RowStr;//文件保存数据使用_暂时不用，但功能得有
    VCI_CAN_OBJ sendbuf[1];//创建sendbuf
    //init sendbuf中的内容
    sendbuf->RemoteFlag=0;//帧格式:0=数据帧，1=远程帧
    sendbuf->ExternFlag=0;//帧类型:0=标准帧，1=扩展帧
    sendbuf->ID=0x770;//帧id
    sendbuf->SendType=1;//=1 时为单次发送（只发送一次，不自动重发）
    sendbuf->TimeFlag=0;//是否使用时间标识。为 1 时 TimeStamp 有效
    sendbuf->TimeStamp=0;//设备接收到某一帧的时间标识。只有智能卡才有时间标识

    //将发送框里面的字符串s去除空格，保存到*C,并反馈出数据的长度到len
    //Str2CharSplitBlank(sendMsg,sendbuf->Data,&sendbuf->DataLen);
    for(int i=1;i<=8;i++)
    {
        sendbuf->Data[i-1]=i;
    }
    ULONG flag =0;//接收发送函数返回值
    SendCnt_CAN0++;
    flag=VCI_Transmit(VCI_USBCAN1,m_DevIndex,0,sendbuf,1); //调用动态链接库发送函数
    //qDebug()<<flag<<"发送状态：=1正常  <1不正常";
    if(flag<1)  //发送不正常
    {
        QMessageBox::warning(this,"警告","发送失败\n");
    }
}
void Widget::Str2CharSplitBlank(QString s, uchar *c,uchar *len)
{
    bool ok;
    QStringList lstr=s.split(" ");
    *len =static_cast<uchar>(lstr.length());
    if(*len!=0){
        for(int i=0;i<*len;i++)
        {
             c[i]=static_cast<unsigned char>(lstr[i].toInt(&ok,16));
             //qDebug()<<"第"<<i<<"个发送的内容：="<<c[i];
        }
    }
}
